<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>数据导入</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/webuploader/0.1.1/webuploader.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.4/themes/default/style.min.css" rel="stylesheet">
<link href="<%=path%>/hplus/css/font-awesome.min93e3.css?v=4.4.0" rel="stylesheet">
<link href="<%=path%>/hplus/css/bootstrap.min14ed.css?v=3.3.6" rel="stylesheet">
<link href="<%=path%>/hplus/css/style.min862f.css?v=4.1.0" rel="stylesheet">
<link href="<%=path%>/hplus/js/plugins/sweetalert/sweetalert2.min.css" rel="stylesheet">
<style type="text/css">
html{font-size:14px;}
button{border-radius:3px;border:1px solid transparent;padding:8px 18px;cursor:pointer;}
.btn-primary {background-color: #1ab394;border-color: #1ab394;color: #FFF;}
.btn-white {background-color: #fff;border-color: #1ab394;color: #1ab394;}
</style>
</head>
<body>


	<div class="tabs-container">
       <ul class="nav nav-tabs" id="menuTabCrm">
       <li class="active"><a data-toggle="tab" href="#tab-1" aria-expanded="true" onclick="clearTab2();">会员导入</a></li>
       <li><a data-toggle="tab" href="#tab-2" aria-expanded="true" onclick="clearTab1();">分组导入</a></li>
       <li><a data-toggle="tab" href="#tab-3" aria-expanded="true" onclick="clearTab12();">导入记录</a></li>
       </ul>
    <div class="tab-content" id="menuTabContentCrm">
       <!-- 会员导入 -->
       <div id="tab-1" class="tab-pane active">									
       <div class="panel-body" id="import1" style="height:360px;">		
		<p>说明：会员导入，是将会员导入至会员列表。重要提示，数据导入后将无法进行删除！</p>
		<span id="attach" align="left" ></span><span id="thelist" style="float:right;width:430px"></span>
		<p align="left" style="color:red;">*支持csv格式，导入文件时请保持每行一个手机号的格式，且导入文件字段与系统字段相同（名称、位置），否则将导入不成功。<a id="downloadTemplate"  style="color:#1ab394;">下载导入模板</a></p>
		<p style="color:red;">*重复数据将自动进行略过处理！</p>
		<div style="height:150px;" id="import1_btn_height"></div>
		<p align="center">		
			<button type="button" class="btn-white" onclick="parent.dataImportDialog.close().remove()">关闭</button>
			<button type="button" class="btn-primary"  onclick="qdSubmit();">确定</button>
		</p>
		</div>														
        </div>
        <!-- 分组导入 -->
        <div id="tab-2" class="tab-pane" >
        <div class="panel-body" style="height:360px;">
        <p>说明：导入分组，是在将会员到入至会员列表的前提下，且将会员导入至已有分组。一个会员可以多次导入至不同分组。</p>
        <!-- 树形控件 -->
        <div style="overflow:auto;height:100px;">
		<div id="jsTree"></div>
		</div>
		<div id="import2"></div>					
		</div>
        </div>
        
        <!-- 导入记录 -->
        <div id="tab-3" class="tab-pane">
        <div class="panel-body" style="height:360px;">
			<p>导入成功记录：<span id="successNum"></span>条</p>
			<p>导入失败记录：<a onclick="exportError();"><u id="errorNum" ></u></a></p>
		</div>
        </div>
        
    </div>
    </div>
	
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/bootcdn/BootCDN/ajax/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.4/jstree.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/webuploader/0.1.1/webuploader.html5only.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/node-uuid/1.4.8/uuid.min.js"></script>
<script src="<%=path%>/hplus/js/plugins/sweetalert/sweetalert2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<script type="text/javascript">
var path = "<%=path%>";
var downloadTemplate;	//下载模板
var beanName;			//beanName
var extensions;			//后缀
var uploader;
var paramJsonStr;
var cid;;

$(function(){
	cid = $.cookie('cid');
	init();
	initTree();
	//初始化成功记录数和失败记录数
	initSusAndError();
});

//普通导入按钮初始化
function init(){
	downloadTemplate = getUrlParam("downloadTemplate");
	beanName = getUrlParam("beanName");
	extensions = getUrlParam("extensions");
	paramJsonStr=getUrlParam("paramJsonStr");
	if(downloadTemplate != null){
		$("#downloadTemplate").attr("href",downloadTemplate);
	}
	
	var $list = $("#thelist");
	var fileId = "";
	var chunks = 0;	//总片数
	uploader = WebUploader.create({
		server : path + "/bigFileUpload/webUploader",
		accept: {
            title: 'CSV',
            // extensions: 'csv'
            mimeTypes: 'text/csv,application/csv,text/comma-separated-values'
        },
		auto : false, //是否自动上传
		pick : {
			id : '#attach',
			name : "multiFile", //这个地方 name 没什么用，和fileVal 配合使用。  
			label : '点击选择文件',
			multiple : false
		},
		fileVal : 'multiFile', //自定义file的name属性，我用的版本是0.1.5 ,打开客户端调试器发现生成的input 的name 没改过来。
		duplicate : true,//是否可重复选择同一文件  
		resize : false,
		chunked : true, //分片处理  
		chunkSize : 20 * 1024 * 1024, //每片20M  
		chunkRetry : 2,//如果失败，则不重试  
		threads : 4,//上传并发数。允许同时最大上传进程数。  
		compress : false,
		disableGlobalDnd : true
	});

	// 当有文件添加进来的时候  
	uploader.on("beforeFileQueued", function(file) {
	      uploader.reset();
	});
	
	
	
	// 当有文件添加进来的时候  
	uploader.on("fileQueued", function(file) {
		if(extensions != null && extensions.indexOf(file.ext) < 0 || "untitled1" == file.name){
	        uploader.reset();
			$list.html("");
			$("#thelist").html("<h4>文件类型不正确！</h4>");
			return ;
		}
		console.log(uploader.getFiles());							
		$list.html("<div id='"+  file.id + "' class='item'>"
				+ "<h4 class='info'>" + file.name + "   等待上传...</h4>");

		fileId = uuid.v4();
	});
	


	//当文件上传成功时触发。  
	uploader.on("uploadSuccess", function(file, response) {
		var paramJsonObj={};
		paramJsonObj = JSON.parse(paramJsonStr);
		var aaa = paramJsonObj.tenantId;
		paramJsonObj.chilkState = chilkState;
		paramJsonObj.fzNum = fzNum;
		paramJsonStr = JSON.stringify(paramJsonObj);
		$.post(path + "/bigFileUpload/uploadSuccess",{
			fileId: fileId,
			chunks: chunks,
			fileExtName: file.ext,
			beanName: beanName,
			paramJsonStr:paramJsonStr
		},function(){
			//$list.html("<div id='"+  file.id + "' class='item'>"
			//		+ "<h4 class='info'>" + file.name + "</h4>"
			//		+ "<p class='state'>上传成功</p>" + "</div>");
			//try{
			//	parent.successDialog("导入成功！");
			//}catch (e) {
			//}
			parent.func_dataTableReload();
			parent.alertImportMember();
			parent.dataImportDialog.close().remove();
		},"json");
	});

	uploader.on("uploadError", function(file) {
		$("#" + file.id).find("p.state").text("上传出错");
		uploader.cancelFile(file);
		uploader.removeFile(file, true);
		uploader.reset();
	});

	uploader.on('uploadBeforeSend', function(block, data) {
		data.uid = fileId;
		data.ext = block.file.ext;
		chunks = block.chunks;
	});
	}
	

	function getUrlParam(key){
		var reg = new RegExp("(^|&)"+ key +"=([^&]*)(&|$)");
	    var r = window.location.search.substr(1).match(reg);
	    if(r!=null)return  unescape(r[2]); return null;
	}
	
	 //导出无法导入的会员信息
	function exportError(){
		 //修改为从redis中获取导出失败的数据
		 window.location.href=path+"/member/exportListErrorForBigMemberImport?cid="+cid;
	}
	//用户选择的分组标识
	var fzNum = ""; 
	//加载分组Tree
	function initTree(){
		$.post(path+"/memberGroup/ajaxGroupTree?status=1",function(data){
			if(data.status != "200"){
				alert("远程请求出错");
				return ;
			}
			if($.jstree.reference('#jsTree') != null){
				$.jstree.reference('#jsTree').destroy();
			}
			var tree = "";
			var option = "";
			tree += "<ul>";
			$.each(data.data,function(i,d){
				var text1 = "";
				var text2 = d.text;
				if(d.text.length > 5){
					text1 = text2;
					text2 = text1.substr(0,4)+"...";
				}
				tree += "<li id='"+d.id+"' data-jstree='{\"type\":\"top\"}' title='"+text1+"'>";
				tree += text2;
				tree += "<ul>";
				
				option += "<option value='"+d.id+"'>"+d.text+"</option>"
				$.each(d.children,function(i2,d2){
					var text1 = "";
					var text2 = d2.text;
					if(d2.text.length > 5){
						text1 = text2;
						text2 = text1.substr(0,4)+"...";
					}
					tree += "<li id='"+d2.id+"' title='"+text1+"'>";
					tree += text2;
				});
				tree += "</ul>";
				tree += "</li>";
			});
			tree += "</ul>";
			$("#jsTree").html(tree);
			//$("#fenlei").html(option);
			
			$("#jsTree").jstree({
				core: {
			    	themes: {
						dots: false
					},
					"check_callback" : true
				},
				"types" : {
				    "default" : {
				      	"icon" : path+"/images/Artboard2.png"
				    },
				    "top" : {
				      	"icon" : path+"/images/Artboard.png"
				    }
				},
				"plugins" : [ "types"]  
			}).on("click.jstree",function(e){
				var nodeId = $.jstree.reference('#jsTree').get_selected()[0];
				var node = $.jstree.reference('#jsTree').get_node(nodeId);
				if(node){		
					if(node.children.length==0 && node.parents.length==2){			
						var groupId = node.id;
						//拿到分组ID
						fzNum = groupId;
					}else{
						fzNum = "";
					}
				}
			});
		},"json");
	}
	
	//0代表点击的是会员导入、1代表点击的是分组导入
	var chilkState = 0;
	function clearTab1(){
		if(chilkState != 1){	
			$("#thelist").text("");
		}
		if($("#import1").html() != null && $("#import1").html() !=""){
		$("#import1_btn_height").css("height", "0px");
		$("#import2").html($("#import1").html());
		$("#import1").html("");
		init();						
		}
		chilkState = 1;
	}
							
	function clearTab2(){
		if(chilkState != 0){		
			$("#thelist").text("");
		}
		if($("#import2").html() != null && $("#import2").html() !=""){
		$("#import1_btn_height").css("height", "150px");
		$("#import1").html($("#import2").html());
		$("#import2").html("");
		init();
		}			
		chilkState = 0;
	}
	
	function clearTab12(){
		$("#thelist").text("");
	}
	
	//初始化失败和成功记录数
	function initSusAndError(){
        $.ajax({
            type: "POST",
            async: false,
            url: "${pageContext.request.contextPath}/member/initSusAndError",
            data: {"cid" : cid},
            dataType: "json",
            timeout: 1000,
            success: function(data){
            	if(data.status == 200){
            		data = data.data;
            		$("#successNum").text(data.successNum);
            		$("#errorNum").text(data.errorNum);
        			//alert(data.errorNum + "----" + data.successNum);
            	}
            }	
		});	
	}
	//确定提交
	function qdSubmit(){
		if($("#thelist").text() == ""){
			alert("请选择需要上传的文件！");
			return;
		}else{
			if(chilkState == 1 && fzNum == ""){
			alert("请选择需要导入的分组！");
			return;
			}
		}
		uploader.upload();
	}
	
	
	

	  
</script>
</html>